import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'package:kasax/commons/commons.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter/cupertino.dart';

/// pull_to_refresh示例
/// https://www.jianshu.com/p/5babe67dac4a
/// 没有更多数据无法控制
class Pull2RefreshDemoHome extends StatefulWidget {
  const Pull2RefreshDemoHome({Key? key}) : super(key: key);

  @override
  _Pull2RefreshDemoHomeState createState() => _Pull2RefreshDemoHomeState();
}

class _Pull2RefreshDemoHomeState extends State<Pull2RefreshDemoHome> {
  List<String> _list = [];

  // 刷新加载控制器
  RefreshController _refreshController =
  RefreshController(initialRefresh: false);

  int numCount = 0;

  // 是否允许上拉加载更多
  bool _enablePullup = true;

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  @override
  void dispose() {
    super.dispose();
    numCount = 0;
    _refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshConfiguration(
      headerBuilder: () => WaterDropHeader(),
      // 头部
      footerBuilder: () => ClassicFooter(),
      // 底部
      headerTriggerDistance: 80.0,
      // 头部触发刷新的距离,
      springDescription: SpringDescription(
        // 自定义回弹
          stiffness: 170,
          damping: 16,
          mass: 1.9),
      maxOverScrollExtent: 100,
      maxUnderScrollExtent: 0,
      enableScrollWhenRefreshCompleted: true,
      enableLoadingWhenFailed: true,
      hideFooterWhenNotFull: false,
      enableBallisticLoad: true,
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("Pull2Refresh"),
          ),
          body: _buildBody(),
        ),
      ),
    );
  }

  _buildBody() {
    return SmartRefresher(
      controller: _refreshController,
      header: ClassicHeader(
        height: 45.0,
        releaseText: '松开手刷新',
        refreshingText: '刷新中',
        completeText: '刷新完成',
        failedText: '刷新失败',
        idleText: '下拉刷新',
      ),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus? mode) {
          Widget body;
          switch (mode!) {
            case LoadStatus.idle:
              body = Text('pull up load');
              break;
            case LoadStatus.loading:
              body = CupertinoActivityIndicator();
              break;
            case LoadStatus.failed:
              body = Text('Load Failed!Click retry!');
              break;
            default:
              body = Text("No more Data");
              break;
          }
          return Container(
            height: 55.0,
            child: Center(
              child: body,
            ),
          );
        },
      ),
      enablePullUp: _enablePullup,
      onRefresh: _onRefresh,
      onLoading: _onLoadMore,
      child: _list.isEmpty
          ? buildLoadingWidget()
          : ListView.separated(
          itemBuilder: (context, index) {
            return ListTile(title: Text("item: ${_list[index]}"));
          },
          separatorBuilder: (context, index) {
            return Divider();
          },
          itemCount: _list.length),
    );
  }

  SmartRefresher buildSmartRefresher() {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: _enablePullup,
      onRefresh: _onRefresh,
      onLoading: _onLoadMore,
      child: ListView.separated(
          itemBuilder: (context, index) {
            return ListTile(title: Text("item: ${_list[index]}"));
          },
          separatorBuilder: (context, index) {
            return Divider();
          },
          itemCount: _list.length),
    );
  }

  void _onRefresh() {
    numCount = 0;
    Future.delayed(Duration(seconds: 2)).then((value) {
      for (int i = 0; i < 20; i++) {
        _list.add("index:$i");
      }
      numCount = _list.length;
      setState(() {
        _refreshController.refreshCompleted();
      });
    });
  }

  void _onLoadMore() {
    Future.delayed(Duration(seconds: 2)).then((value) {
      setState(() {
        List<String> list = [];
        for (int i = 0; i < 20; i++) {
          list.add("index:(${numCount + i})");
        }
        numCount += list.length;
        _list.addAll(list);
        if (_list.length >= 100) {
          _enablePullup = false;
          // _refreshController.loadComplete();
        } else {
          // _enablePullup = true;
        }
        _refreshController.loadComplete();
      });
    });
  }
}
